'use client';

import React, { useCallback } from 'react';
import { ArrowLeftIcon, CloudIcon } from '@heroicons/react/16/solid';
import { ThemeController } from 'src/app/components/ThemeController';
import { useParams, useRouter } from 'next/navigation';
import { useRequest } from 'ahooks';
import { getImage } from 'src/actions/image';
import { Confirm } from 'src/components/Confirm';
import { ImageEditor } from './ImageEditor';
import { Aside } from './Aside';
import { Resizable, ResizableProps, ResizeInfo } from 'src/components/Resizable';
import clsx from 'clsx';

const resizeRange: ResizableProps['resizeRange'] = [
  [0, 150],
  [-350, 20],
];

export default function Main() {
  const router = useRouter();
  const { imageId } = useParams();

  // Requests
  const { data: imageInfo, loading } = useRequest(getImage, {
    defaultParams: [imageId as string],
    debounceWait: 300,
  });

  // Handlers
  const handleSP = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    e.preventDefault();
  }, []);

  const handleResizeX = useCallback(({ movement, target, targetStartRect }: ResizeInfo) => {
    const width = targetStartRect.width + movement.x;
    target.style.width = `${width}px`;
  }, []);

  const handleResizeY = useCallback(({ movement, target, targetStartRect }: ResizeInfo) => {
    const height = targetStartRect.height - movement.y;
    target.style.height = `${height}px`;
  }, []);

  const handleX = useCallback(
    (resizing: boolean) => (
      <div
        role="button"
        aria-label="splitter"
        className="absolute right-0 top-0 w-5 h-full flex justify-end cursor-ew-resize z-50 select-none group"
        onClick={handleSP}
        title="拖动调整宽度"
      >
        <div
          className={clsx(
            'w-1.5 h-full transition-colors group-[&:hover]:bg-purple-500/50',
            resizing && 'bg-purple-500/50'
          )}
        />
      </div>
    ),
    [handleSP]
  );

  const handleY = useCallback(
    (resizing: boolean) => (
      <div
        role="button"
        aria-label="splitter"
        className="absolute left-0 top-0 w-full h-5 flex cursor-ns-resize z-50 select-none group"
        onClick={handleSP}
        title="拖动调整高度"
      >
        <div
          className={clsx(
            'w-full h-1.5 transition-colors group-[&:hover]:bg-purple-500/50',
            resizing && 'bg-purple-500/50'
          )}
        />
      </div>
    ),
    [handleSP]
  );

  if (loading || !imageInfo) {
    return (
      <div className="flex items-center justify-center h-screen">
        <span className="loading loading-ball loading-xl" />
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center justify-center h-screen overflow-hidden bg-base-200">
      <div className="flex-none navbar h-16 bg-base-100 px-5 shadow-sm relative z-10">
        <div className="flex-none">
          <button type="button" className="btn btn-circle" onClick={() => router.back()}>
            <ArrowLeftIcon className="size-4" />
          </button>
        </div>
        <div className="flex-1 px-5 truncate">
          <span className="text-base font-bold">{imageInfo?.fileName}</span>
        </div>
        <div className="flex-none flex items-center gap-5">
          <ThemeController />
          <Confirm title="另存为" content="表单信息">
            <button type="button" className="btn rounded-full text-gray-700 dark:text-gray-300">
              另存为
            </button>
          </Confirm>
          <Confirm
            title="保存图片"
            content="保存后将更新原图信息，确定保存原图吗？"
            onConfirm={() => {
              return new Promise((resolve) => {
                // 模拟保存操作
                setTimeout(() => {
                  resolve();
                  // 或者 reject(new Error('保存失败'));
                }, 1000);
              });
            }}
          >
            <button type="button" className="btn btn-primary rounded-full">
              <CloudIcon className="size-4" />
              保存
            </button>
          </Confirm>
        </div>
      </div>
      <div className="flex-1 w-full flex overflow-hidden">
        <Resizable renderHandle={handleX} onResize={handleResizeX} resizeRange={resizeRange}>
          <Aside className="flex-none relative" imageInfo={imageInfo} />
        </Resizable>
        <main className="flex-1 flex flex-col">
          <ImageEditor className="flex-1" imageInfo={imageInfo} />
          <Resizable renderHandle={handleY} onResize={handleResizeY} resizeRange={resizeRange}>
            <div className="flex-none relative h-20 border-t border-gray-200 dark:border-neutral-700">
              code
              <span>xxx</span>
            </div>
          </Resizable>
        </main>
      </div>
    </div>
  );
}
